/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src.view.loan;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import org.primefaces.context.RequestContext;
import org.primefaces.event.CloseEvent;
import src.domain.finance.Bv;
import src.domain.loan.Loan;
import src.domain.loan.LoanInstallment;
import src.domain.loan.Loanpmt;
import src.domain.saving.Saving;
import src.domain.security.Users;
import src.domain.system.Numbering;
import src.services.CRUEDService;
import src.services.finance.BankModel;
import src.services.finance.BvModel;
import src.services.loan.LoanInstallmentModel;
import src.services.loan.LoanModel;
import src.services.loan.LoanpmtModel;
import src.services.saving.SavingModel;
import src.util.Constanta;
import src.util.Messager;
import src.util.Utils;
import src.view.security.LoginBean;

/**
 *
 * @author jay
 */
@ManagedBean
@SessionScoped
public class LoanpmtBean implements Serializable {

    private List<SelectItem> availableBank;  
    private Loanpmt loanpmt;  
    private LoanInstallment installment;
    private boolean editMode = false, insertionMode=false;
    private BankModel bankHelper; 
    private LoanpmtModel pmtHelper;
    private Integer branchId;
    private String savingNo, savingOwner, cif;
    private boolean showLookup=false;
    private BigDecimal saldo;
    private Users users;      
    
    public LoanpmtBean() {
        super();
        ambilUser();
        this.bankHelper = new BankModel(); 
        this.pmtHelper = new LoanpmtModel();
        
        newData();
        editMode = false;
    }
    
    public boolean isEditMode() {
        return editMode;
    }
    
    public Loanpmt getLoanpmt() {
        return loanpmt;
    }

    public void setLoanpmt(Loanpmt loanpmt) {
        this.loanpmt = loanpmt;
    }

    public List<SelectItem> getAvailableBank() {
        return availableBank;
    }

    public String getSavingNo() {
        return savingNo;
    }

    public BigDecimal getSaldo() {
        return saldo;
    }

    public String getSavingOwner() {
        return savingOwner;
    }

    public String getCif() {
        return cif;
    }

    private String newNumber() {
        Numbering currNo = new CRUEDService().getNextTrxNumber(5, 0, 0, 1);
        return currNo.getTrxNum();
    }

    public void getLoan(String accntNo) {
        boolean found=false;
        this.installment=null;
        if ("null".equals(accntNo)) accntNo = loanpmt.getLoan().getLoanNo();
        
        if (accntNo!=null ) {
            LoanModel helper = new LoanModel();
            Loan loan = helper.getByAccount(accntNo, Constanta.LOANSTATUS_RUNNING);
                        
            if (loan==null) {
                Messager.showWarning("accntNotFound");
                this.loanpmt.setLoan(new Loan());
                
            } else {
                this.installment = new LoanInstallmentModel().nextPayment(loan.getLoanId());
                //Loanpmt hitung = pmtHelper.calculateAmount(loan.getLoanId());
                this.loanpmt.setAmount(installment.getInterestAmount().add(installment.getPrincipleAmount()));
                this.loanpmt.setPrincipalAmount(installment.getPrincipleAmount());
                this.loanpmt.setInterestAmount(installment.getInterestAmount());
                this.loanpmt.setLoan(loan);
                
                found=true;
            }
        }
        RequestContext.getCurrentInstance().addCallbackParam("success", found); 
    }
    
    public void getSaving(String accntNo) {
        if ("null".equals(accntNo)) accntNo = savingNo;
        
        boolean found=false;
        if (accntNo!=null ) {
            
            Saving saving = new SavingModel().getByAccount(accntNo);
            if (saving==null) {
                this.loanpmt.setPaymentSavingId(null);
                this.cif=null;
                this.savingNo=null;
                this.savingOwner=null;
                this.cif=null;
                this.saldo= new BigDecimal(0);
                Messager.showWarning("accntNotFound");
                
            } else {
                found=true;
                this.loanpmt.setPaymentSavingId(saving.getSavaccntId());
                this.savingNo=saving.getAccountNo();
                this.savingOwner=saving.getCustomer().getCustomerName();
                this.cif=saving.getCustomer().getCif();
                this.saldo= saving.getBalance();
                loanpmt.setBankId(null);
            }   
        }
        RequestContext.getCurrentInstance().addCallbackParam("success", found); 
    }
    
    public void handleBankSelected() {
         this.loanpmt.setPaymentSavingId(null);
         this.savingNo=null;
         this.savingOwner=null;
         this.cif=null;
         this.saldo= new BigDecimal(0);
    }
    
    public void getBV() {
        String bvNo = loanpmt.getBv().getBvNo();
        if (!bvNo.equals("") && bvNo!=null ) {
            BvModel helper = new BvModel();
            Bv bv = helper.getByAccount(bvNo);
                        
            if (bv==null) {
                Messager.showWarning("accntNotFound");
                this.loanpmt.setLoan(new Loan());
                
            } else this.loanpmt.setBv(bv);
        }
    }
    
    public void search() {}
        
    private void initForm() {
        this.editMode = true;
        this.showLookup=false;
        this.savingNo = null;
        this.savingOwner = null;
        this.cif = null;
        
        this.saldo= new BigDecimal(0);
        this.availableBank = bankHelper.listAll();
    }
        
    public final void newData() {  
        initForm();
        if (this.loanpmt!=null) loanpmt = null;
        this.loanpmt = new Loanpmt();
        this.loanpmt.setBranchId(branchId);
        this.loanpmt.setUserId(users.getUserId());
        insertionMode = true;
    }
    
    public void openData() {
        initForm();
        insertionMode = false;
    }
        
    public boolean validate() {
        
        if (loanpmt.getPaymentSavingId() != null && loanpmt.getAmount().compareTo(saldo) > 0 ) {
            Messager.showWarning("balanceKurang");
            return false;
        }
        return true;
    }
    
    public void save() {
        
        if (validate()) {
            loanpmt.setPaymentNo(newNumber());

            String log = Utils.logActions(users.getUserName(), loanpmt.getPaymentDate());
            loanpmt.setLogCreate(log);
            loanpmt.setLogPost(log);
            loanpmt.setPosted(true);

            if(loanpmt.getBankId()==-1) loanpmt.setBankId(null);

            installment.setPaid(true);
            boolean success = pmtHelper.saveData(loanpmt, installment);

            // re-insert
            if (!success && insertionMode) loanpmt.setLoanpmtId(null);
            else insertionMode = false;

            this.editMode = !success;
            Messager.showSaveUpdateStatus(success);  
            RequestContext.getCurrentInstance().addCallbackParam("success", success); 
        }
    }
    
    public void delete() {
                  
    }

    public boolean isShowLookup() {
        return showLookup;
    }

    public void setShowLookup(boolean showLookup) {
        this.showLookup = showLookup;
    }
    
    public void handleCloseLookup(CloseEvent event) {
        this.showLookup=false;
    }

    public void setSavingNo(String savingNo) {
        this.savingNo = savingNo;
    }
        
     private void ambilUser() {
        FacesContext context = FacesContext.getCurrentInstance();
        LoginBean logBean = (LoginBean) context.getApplication().evaluateExpressionGet(context, "#{loginBean}", LoginBean.class);
        this.users = logBean.getSelectedUser();
        this.branchId = users.getBranch().getBranchId();
    }
}
